<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require_once APPPATH.'controllers/Base.php';
class Route extends Base {

    public $route_rule = [
        ['field' => 'departure', 'label'=>'出发地', 'rules' => 'required'],
        ['field' => 'departure_city', 'label'=>'出发城市', 'rules' => 'required'],
        ['field' => 'departure_time', 'label'=>'出发时间', 'rules' => 'required'],
        ['field' => 'destination', 'label'=>'目的地', 'rules' => 'required'],
        ['field' => 'destination_city', 'label'=>'目的城市', 'rules' => 'required'],
        ['field' => 'seat_num', 'label'=>'座位/人数', 'rules' => 'required'],
    ];

    public function __construct()
    {
        parent::__construct();
        $this->load->model('route_model');
        $this->load->library('form_validation');
    }

    public function index()
    {
        $result = $this->route_model->getRoutes();
        $this->success($result);
    }

    public function route()
    {
        $route_id = $this->input->get('route_id');
        $result = $this->route_model->getRoute($route_id);
        $this->success($result);
    }

    public function createDriverRoute()
    {
        $user = $this->userCheck();
        $this->validationRoute();

        $data = $this->input->post();
        $data['user_id'] = $user['user_id'];

        $result = $this->route_model->createDriverRoute($data);
        if(!$result){
            $this->error('创建失败！');
        }
        $this->success($result);
    }

    public function createPassengerRoute()
    {
        $user = $this->userCheck();
        $this->validationRoute();

        $data = $this->input->post();
        $data['user_id'] = $user['user_id'];

        $result = $this->route_model->createPassengerRoute($data);
        if(!$result){
            $this->error('创建失败！');
        }
        $this->success($result);
    }

    //司机邀请乘客加入行程
    public function invitePassenger()
    {
        $this->userCheck();
        $data = $this->input->post();

        $result = $this->route_model->invitePassenger($data);
        if(!$result){
            $this->error('邀请失败！');
        }
        $this->success('邀请已发出,请等待乘客确认!');
    }

    //乘客申请加入司机行程
    public function applyDriver()
    {
        $user = $this->userCheck();
        $data = $this->input->post();

        $data['user_id'] = $user['user_id'];
        $result = $this->route_model->applyDriver($data);
        if(!$result){
            $this->error('申请已发出,请等待车主确认!');
        }
        $this->success($result);
    }

    private function validationRoute()
    {
        $this->form_validation->set_rules($this->route_rule);
        if($this->form_validation->run() == FALSE){
            $this->error(reset($this->form_validation->error_array()));
        }
    }

}
